//
//  HCForgetViewController.m
//  HappyChildren
//
//  Created by WillyZhao on 2017/3/2.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCForgetViewController.h"

@interface HCForgetViewController () {
    UITextField *phoneField_;
    UITextField *pwdField_;
    UIButton *button_;
    UITextField *pwd;
    UITextField *re_pwd;
    NSString *smsCode;
}

@end

@implementation HCForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.textTitle = @"忘记密码";
    
    UIView *forgetView = [[[NSBundle mainBundle] loadNibNamed:@"andnoadnoiaonis" owner:self options:nil]firstObject];
    forgetView.frame = CGRectMake(0, 0, self.centerView.frame.size.width, self.centerView.frame.size.height);
    forgetView.backgroundColor = YBKRGBCOLOR(241, 241, 241, 1);
    [self.centerView addSubview:forgetView];
    
    UIView *lineView = (UIView *)[forgetView viewWithTag:104];
    lineView.backgroundColor = forgetView.backgroundColor;
    
    UIView *lineView1 = (UIView *)[forgetView viewWithTag:9876];
    lineView1.backgroundColor = lineView.backgroundColor;
    
    UIView *lineView2 = (UIView *)[forgetView viewWithTag:9875];
    lineView2.backgroundColor = lineView.backgroundColor;
    
    pwd = (UITextField *)[forgetView viewWithTag:1044];     //输入密码
    re_pwd = (UITextField *)[forgetView viewWithTag:1045];  //再次输入密码
    
    
    UIButton *btn = (UIButton *)[forgetView viewWithTag:9874];
    btn.backgroundColor = YBKRGBCOLOR(240, 96, 96, 1);
    [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    btn.titleLabel.font = YBKSystemFont(YBKAdaptiveFont(13));
    [btn addTarget:self action:@selector(smsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    phoneField_ = (UITextField *)[forgetView viewWithTag:101];
    pwdField_ = (UITextField *)[forgetView viewWithTag:102];
//    pwdField_.secureTextEntry = YES;
    button_ = (UIButton *)[forgetView viewWithTag:103];
    button_.backgroundColor = YBKRGBCOLOR(240, 96, 96, 1);
    [button_ addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.dataRequest.delegate = self;
    // Do any additional setup after loading the view.
}

-(void)smsBtnAction:(UIButton *)btn {
    if (![PublicFunction checkTelNumber:phoneField_.text]) {
        [XHToast showBottomWithText:@"手机号码格式不正确"];
    }else{
        [self.dataRequest postHC_RegisterCheck:phoneField_.text checkString:@"0"];
        [self theWayLessTimeButton:btn WithTime:60 AndTitle:nil];
    }
}

#pragma mark -- 倒计时按钮
-(void)theWayLessTimeButton:(UIButton *)button WithTime:(NSInteger)time AndTitle:(NSString *)title{
    //    UIButton *buttonLess = (UIButton *)button;
    button.titleLabel.numberOfLines = 0;
    __block int timeout= (int)time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 创建一个定时器(dispatch_source_t本质还是个OC对象,创建出来的对象需要强引用)
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 设置定时器的各种属性(几时开始任务，每隔多长时间执行一次)
    // GCD的时间参数，一般是纳秒(1秒 = 10的9次方纳秒)
    // 何时开始执行第一个任务
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)); //比当前时间晚1秒
    //    dispatch_time_t start = DISPATCH_TIME_NOW;// 当前时间执行
    uint64_t interval= 2.0 * NSEC_PER_SEC;
    dispatch_source_set_timer(self.timer, start, interval, 0); // NSEC_PER_SEC 纳秒
    // 设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        
        timeout--;
        //        记好了刷新UI的时候一定要在主队列中刷新,就是主线程.
        dispatch_async(dispatch_get_main_queue(), ^{
            button.userInteractionEnabled=NO;
            [button setTitle:[NSString stringWithFormat:@"   %ds后重新获取   ",timeout] forState:UIControlStateNormal];
            //            NSLog(@"-----%d",timeout);
            if (timeout == 1) {
                
                [button setTitle:@"  获取验证码   " forState:UIControlStateNormal];
                button.userInteractionEnabled=YES;
                dispatch_cancel(self.timer);
                self.timer = nil;
            }
            
        });
        /*
         
         GCD的定时器要比NStimer的定时器要精确的多.
         
         
         
         
         */
        
    });
    // 启动定时器
    dispatch_resume(self.timer);
    
}


-(void)buttonAction:(UIButton *)btn {
    
    if ([pwdField_.text isEqualToString:smsCode]) {
        if ([pwd.text length]>16||[pwd.text length]<6) {
            [XHToast showBottomWithText:@"密码位数不正确"];
        }else{
            //发起网络请求
            if ([pwd.text isEqualToString:re_pwd.text]) {
                [self.dataRequest postHC_FoegetPWD:phoneField_.text andpwd:pwd.text];
            }else{
                [XHToast showBottomWithText:@"两次输入密码不相同"];
            }
        }
    }else{
        [XHToast showBottomWithText:@"验证码错误"];
    }

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

-(void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    NSLog(@"修改密码成功:%@",dictionary);
    
    if (aType == HC_REGISTER_CHECK) {
        smsCode = [NSString stringWithFormat:@"%@",dictionary[@"param"]];
    }else{
        if ([dictionary[@"stat"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改密码成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改密码失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }
 
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
